package com.mycat.auth.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mycat.auth.dao.mapper.RefRoleAuthMapper;
import com.mycat.auth.dao.mapper.RoleMapper;
import com.mycat.auth.domain.RefRoleAuth;
import com.mycat.auth.domain.Role;
import com.mycat.auth.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author roger.
 * @email luojie@yzworld.cn
 * @date 2016/10/9
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RefRoleAuthMapper refRoleAuthMapper;

    @Override
    public void addRole(Role role) {
        if(null != role){
            role.setCreateDate(new Date());
        }
        roleMapper.insertSelective(role);
    }

    @Override
    public void delRole(Integer[] ids) {
        for (Integer id : ids){
            roleMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void updateRole(Role role) {
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public Role findRole(Role role) {
        return roleMapper.selectRole(role);
    }

    @Override
    public PageInfo<Role> findRoles(Page<Role> page) {
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<Role> roles = roleMapper.selectAll();
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return pageInfo;
    }

    @Override
    public List<Role> findRoles() {
        return roleMapper.selectAll();
    }

    @Override
    public void addResource(Integer roleId, Integer[] resourceIds) {
        refRoleAuthMapper.deleteRoleResource(roleId);
        List<RefRoleAuth> refRoleAuths = new ArrayList<>();
        for (Integer resourceId : resourceIds){
            refRoleAuths.add(new RefRoleAuth(roleId,resourceId));
        }
        if(refRoleAuths.size() > 0){
            refRoleAuthMapper.insertList(refRoleAuths);
        }
    }
}
